package com.party.mem.biz.system.member;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.utils.PasswordUtils;
import com.party.common.utils.PinyinUtil;
import com.party.core.exception.BusinessException;
import com.party.core.model.AuditStatus;
import com.party.core.model.YesNoStatus;
import com.party.core.model.commune.CMemberInfo;
import com.party.core.model.commune.CRoute;
import com.party.core.model.commune.CRouteInfo;
import com.party.core.model.commune.IntegralType;
import com.party.core.model.member.Expert;
import com.party.core.model.member.Member;
import com.party.core.model.member.PartnerMember;
import com.party.core.service.commune.*;
import com.party.core.service.member.IExpertService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.PartnerMemberToBizService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.mem.biz.file.FileBizService;
import com.party.mem.biz.member.CIntegralBizToService;
import com.party.mem.biz.member.MemberMgmtService;
import com.party.mem.biz.member.MemberRouteBizService;
import com.party.mem.utils.MyBeanUtils;
import com.party.mem.utils.RealmUtils;
import com.party.mem.web.security.CurrentUser;
import com.party.notify.notifyPush.servce.INotifySendService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MemberBizService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IExpertService expertService;

    @Autowired
    private INotifySendService notifySendService;

    @Autowired
    private ICMemberInfoService cMemberInfoService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private PartnerMemberToBizService partnerMemberToBizService;

    @Autowired
    private ICMemberRecommendService memberRecommendService;

    @Autowired
    private ICIntegralBizService integralBizService;

    @Autowired
    private ICRouteService routeService;

    @Autowired
    private MemberRouteBizService memberRouteBizService;

    @Autowired
    private ICRouteInfoService routeInfoService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private CIntegralBizToService cIntegralBizToService;

    @Autowired
    private MemberMgmtService memberMgmtService;
    /**
     * 保存业务数据
     *
     * @param member
     * @return
     * @throws Exception
     */
    public Member saveBiz(Member member, Integer type) throws Exception {
        if (StringUtils.isEmpty(member.getId())) {
            // 新增
            String realname = member.getRealname();
            if (StringUtils.isNotBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                member.setRealname(realname);
                member.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            if (StringUtils.isNotEmpty(member.getPassword())) {
                member.setPassword(PasswordUtils.encryptPassword(member.getPassword()));
            } else {
                member.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            }
            member.setPicNum(0);
            member.setType(Member.MEMBER_PERSONAL);
            if (member.getIsAdmin() == null) {
                member.setIsAdmin(YesNoStatus.NO.getCode());
            }
            if (member.getIsExpert() == null) {
                member.setIsExpert(YesNoStatus.NO.getCode());
            }
            if (member.getIsDistributor() == null) {
                member.setIsDistributor(YesNoStatus.NO.getCode());
            }
            if (member.getIsPartner() == null) {
                member.setIsPartner(YesNoStatus.NO.getCode());
            }
            if (member.getIsCopartner() == null) {
                member.setIsCopartner(YesNoStatus.NO_NEW.getCode());
            }
            if (member.getIsCosponsor() == null) {
                member.setIsCosponsor(YesNoStatus.NO.getCode());
            }
            member.setType(type);
            memberService.insert(member);// 保存
            return member;
        } else {
            // 编辑
            Member t = memberService.get(member.getId());// 从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(member, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
            if (StringUtils.isNotEmpty(member.getPassword())) {
                member.setPassword(PasswordUtils.encryptPassword(member.getPassword()));
            }
            String realname = t.getRealname();
            if (StringUtils.isNoneBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                t.setRealname(realname);
                t.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberService.update(t);
            return t;
        }
    }

    /**
     * 保存达人
     *
     * @param entity
     */
    public void saveExpert(Member entity) {
        Expert ex = expertService.findByMemberId(entity.getId());
        Integer isExpert = entity.getIsExpert();
        if (ex == null && isExpert != null && isExpert == 1) {
            ex = new Expert();
            ex.setMemberId(entity.getId());
            expertService.insert(ex);
            notifySendService.sendExpertApprove(entity.getId());
        } else if (ex != null && isExpert != null && isExpert == 0) {
            expertService.delete(ex.getId());
            notifySendService.sendExpertCancel(entity.getId());
        }
    }

    /**
     * 创建会员，并初始化
     *
     * @return 会员实体
     */
    @Transactional
    public Member createMember(Integer type) {
        Member member = new Member();
        member.setUserStatus(Integer.parseInt(AuditStatus.AUDITING.getCode()));//默认未审核
        // 联合发起
        member.setIsCopartner(YesNoStatus.NO_NEW.getCode());
        // 合作商
        member.setIsPartner(YesNoStatus.NO.getCode());
        // 管理员
        member.setIsAdmin(YesNoStatus.NO.getCode());
        // 达人
        member.setIsExpert(YesNoStatus.NO.getCode());
        // 分销商
        member.setIsDistributor(YesNoStatus.NO.getCode());
        // 合作渠道
        member.setIsCosponsor(YesNoStatus.NO.getCode());
        member.setPicNum(0);
        member.setIsOpen(YesNoStatus.NO.getCode());
        member.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
        member.setType(type);
        memberService.insert(member);//保存会员

        return member;
    }

    /**
     * @Description:编辑C端用户
     * @Param:CMemberInfo
     * @return:Member
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    public Member saveOrUpdateCmember(CMemberInfo input) throws Exception {
        String partnerId = RealmUtils.getCurrentUser().getId();
        String xzgs_partnerId = RealmUtils.getCurrentUser().getPartnerId();
        if(StringUtils.isEmpty(xzgs_partnerId)){
            xzgs_partnerId = partnerId;
        }
        Member member = null;
        if (StringUtils.isNotEmpty(input.getPmId()))
        {
            PartnerMember partnerMember = partnerMemberService.get(input.getPmId());
            partnerId = partnerMember.getPartnerId();
        }
        //用户主体
        if (StringUtils.isEmpty(input.getId())) {
            boolean bl = partnerMemberToBizService.checkPartnerUser(partnerId, input.getId(), input.getMobile());
            if (!bl) {
                throw new BusinessException("手机号已存在");
            }
            //初始化member
            member = this.createMember(Member.MEMBER_PERSONAL);

            member.setLogo(input.getLogo());
            member.setJobTitle(input.getJobTitle());
            member.setMobile(input.getMobile());
            member.setCompany(input.getCompany());
            member.setCity(input.getCity());
            member.setSex(input.getSex());
            member.setRealname(PinyinUtil.filterEmoji(input.getRealname(), ""));
            member.setPinyin(PinyinUtil.hanziToPinyin(member.getRealname(), ""));
            member.setWechatNum(input.getWechatNum());
            member.setWantRes(input.getWantRes());
            memberService.update(member);

        } else {
            // 从数据库取出记录的值
            member = memberService.get(input.getId());
            // 将编辑表单中的非NULL值覆盖数据库记录中的值
            MyBeanUtils.copyBeanNotNull2Bean(input, member);

            String realname = input.getRealname();
            if (StringUtils.isNoneBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                member.setRealname(realname);
                member.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberService.update(member);
        }

        //用户附属信息主体
        CMemberInfo cMemberInfo = cMemberInfoService.getByMemberId(member.getId());
        if (null == cMemberInfo) {
            input.setMemberId(member.getId());
            cMemberInfoService.insert(input);
            calMemberRouteInfo(input,member.getId());
        } else {
            if ((StringUtils.isNotEmpty(input.getcLng()) && !input.getcLng().equals(cMemberInfo.getcLng())) ||
                    (StringUtils.isNotEmpty(input.gethLng()) && !input.gethLng().equals(cMemberInfo.gethLng())))
            {
                calMemberRouteInfo(input,member.getId());
            }
            cMemberInfo.setHobby(input.getHobby());
            cMemberInfo.setAddress(input.getAddress());
            cMemberInfo.setEmail(input.getEmail());
            cMemberInfo.setManifesto(input.getManifesto());
            cMemberInfo.setSynopsis(input.getSynopsis());
            cMemberInfo.setDistrict(input.getDistrict());
            cMemberInfo.setLeagueJob(input.getLeagueJob());
            cMemberInfo.sethCityId(input.gethCityId());
            cMemberInfo.sethArea(input.gethArea());
            cMemberInfo.sethPlace(input.gethPlace());
            cMemberInfo.sethLat(input.gethLat());
            cMemberInfo.sethLng(input.gethLng());
            cMemberInfo.setcCityId(input.getcCityId());
            cMemberInfo.setcArea(input.getcArea());
            cMemberInfo.setcPlace(input.getcPlace());
            cMemberInfo.setcLat(input.getcLat());
            cMemberInfo.setcLng(input.getcLng());
            cMemberInfo.setMainBus(input.getMainBus());
            cMemberInfoService.update(cMemberInfo);
        }


        //机构用户关系维护
        PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(partnerId, member.getId());
        PartnerMember mainOrg = partnerMemberService.getMainOrg(member.getId(), partnerId);
        boolean hasZxgsPartner = memberMgmtService.hasZxgsPartner(partnerId, member.getId());

        if (null == partnerMember && !hasZxgsPartner) {
            partnerMember = new PartnerMember();
            partnerMember.setPartnerId(partnerId);
            partnerMember.setMemberId(member.getId());

            if (mainOrg == null) {
                partnerMember.setUserSerial(input.getUserSerial());
                partnerMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
            } else {
                mainOrg.setUserSerial(input.getUserSerial());
                partnerMemberService.update(mainOrg);
            }
            partnerMemberService.insert(partnerMember);
            if(mainOrg  == null){
                //如果主分社为空，说明是第一次进入分社
                //添加赠送积分
                try {
                    integralBizService.insertSystemCIntegralItem(null,xzgs_partnerId,partnerMember,null, IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode());
                }catch (Exception e){
                    logger.error("添加赠送积分失败:"+ JSONObject.toJSONString(member),e.getMessage());
                }
            }
        }else if (mainOrg.getId().equals(partnerMember.getId())){
            partnerMember.setUserSerial(input.getUserSerial());
            partnerMemberService.update(partnerMember);
        } else
        {
            mainOrg.setUserSerial(input.getUserSerial());
            partnerMemberService.update(mainOrg);
        }
        //生成个人资料小程序码
        cIntegralBizToService.generateXZGSXCXQRCode(partnerMember.getPartnerId(),partnerMember.getMemberId());
        return member;
    }

    private void calMemberRouteInfo(CMemberInfo input, String memberId)
    {
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        Map<String,Object> params = Maps.newHashMap();
        List<String> orgIds = memberGroupService.getChildWithMy(currentUser.getId());
        params.put("orgIds",orgIds);
        List<CRoute> cRouteList = routeService.webPageList(params,null);
        //公司地址
        List<Map<String, Object>> companyAddress = new ArrayList<>();
        //家地址
        List<Map<String, Object>> homeAddress = new ArrayList<>();

        if (StringUtils.isNotEmpty(input.getcLat()) && StringUtils.isNotEmpty(input.getcLng()))
        {
            Map<String,Object> companyAddressMap = new HashMap<>();
            companyAddressMap.put("cLat",input.getcLat());
            companyAddressMap.put("cLng",input.getcLng());
            companyAddressMap.put("memberId",input.getId());
            companyAddress.add(companyAddressMap);
        }

        if (StringUtils.isNotEmpty(input.gethLat()) && StringUtils.isNotEmpty(input.gethLng()))
        {
            Map<String,Object> homeAddressMap = new HashMap<>();
            homeAddressMap.put("hLat",input.gethLat());
            homeAddressMap.put("hLng",input.gethLng());
            homeAddressMap.put("memberId",input.getId());
            homeAddress.add(homeAddressMap);
        }
        Integer total = 0;
        if (companyAddress.size() >0)
        {
            total +=4;
        }
        if (homeAddress.size() > 0 )
        {
            total +=4;
        }
        if (companyAddress.size() >0 || homeAddress.size() >0)
        {
            for (CRoute cRoute : cRouteList) {

                List<CRouteInfo> cRouteInfoList = routeInfoService.getRouteByMemberIdAndRouteId(cRoute.getId(),memberId);
                Integer size = cRouteInfoList.size();
                if (size > 0)
                {
                    for (CRouteInfo cRouteInfo : cRouteInfoList) {
                        routeInfoService.delete(cRouteInfo.getId());
                    }
                }
                Integer routeInfoTotal = cRoute.getRouteInfoTotal();
                cRoute.setRouteInfoTotal(routeInfoTotal - size + total);
                routeService.update(cRoute);
                memberRouteBizService.calDistanceAndTime(cRoute,companyAddress,homeAddress,cRoute.getCreateBy());
            }
        }

    }
}
